import { createApp, ref, h, markRaw, defineComponent } from 'vue';
import Modal from './Modal.vue';

const modalPlugin = {
  install(app) {
    // 创建一个新的 div 用于存放 modal 组件
    const modalContainer = document.createElement('div');
    document.body.appendChild(modalContainer);

    // 创建一个 Vue 应用来管理模态框
    const modalApp = createApp(
      defineComponent({
        setup() {
          const isVisible = ref(false);
          const title = ref('');
          const content = ref(null);

          const open = (newTitle, newContent) => {
            title.value = newTitle;
            content.value = markRaw(newContent); // markRaw 确保组件不会被 Vue 代理； vue 会主动代理每个组件，如果组件不需要响应式那就可以使用markRaw取消掉，避免vue加工该组件
            isVisible.value = true;
            // console.log(h(content.value))
            console.log(newTitle)

            setTimeout(() => {
              close()
            }, 2000)
          };

          const close = () => {
            isVisible.value = false;
          };

          return {
            isVisible,
            title,
            content,
            open,
            close
          };
        },
        render() {
          return h(Modal, { visible: this.isVisible, title: this.title, onClose: this.close }, {
            default: () => (this.content ? h(this.content) : null)
          });
        }
      })
    );

    const modalInstance = modalApp.mount(modalContainer);

    // 确保方法正确绑定到实例
    app.config.globalProperties.$modal = {
      open: (...args) => modalInstance.open(...args),
      close: () => modalInstance.close()
    };

    app.config.globalProperties.$modalContainer = modalContainer;

    // 在应用销毁时清理
    app.mixin({
      onUnmounted() {
        console.log('什么时候哦', app.config.globalProperties)
        const modalContainer = app.config.globalProperties.$modalContainer;
        if (modalContainer && modalContainer.parentNode) {
          modalApp.unmount();
          document.body.removeChild(modalContainer);
        }
      }
    });
  }
};

export default modalPlugin;
